package com.eaero.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.eaero.CommonResp;
import com.eaero.entity.TraceHandover;
import com.eaero.entity.TraceHandoverDetail;
import com.eaero.entity.TraceStoresloc;
import com.eaero.entity.TraceTool;
import com.eaero.mapper.TraceHandoverMapper;
import com.eaero.service.ITraceHandoverDetailService;
import com.eaero.service.ITraceHandoverService;
import com.eaero.service.ITraceStoreslocService;
import com.eaero.service.ITraceToolService;
import com.eaero.vo.CancelHandoverRequest;
import com.eaero.vo.HandingOfRequest;
import com.eaero.vo.HandoverInfoRequest;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.net.URLDecoder;
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.time.format.DateTimeFormatter;
import java.util.List;
import java.util.stream.Collectors;

/**
 * <p>
 * 服务实现类
 * </p>
 *
 * @author zb
 * @since 2023-03-14
 */
@Service
public class TraceHandoverServiceImpl extends ServiceImpl<TraceHandoverMapper, TraceHandover> implements ITraceHandoverService {

    @Autowired
    private ITraceHandoverDetailService detailService;

    @Autowired
    private ITraceToolService toolService;

    @Autowired
    private ITraceStoreslocService storeslocService;

    /**
     * 生成交班信息
     *
     * @param request
     * @return
     */
    @Override
    @Transactional
    public CommonResp handingOf(HandingOfRequest request) {
        if (!(StrUtil.isNotBlank(request.getWarhouse())
                && StrUtil.isNotBlank(request.getUserCode())
                && StrUtil.isNotBlank(request.getHoDate())
                && StrUtil.isNotBlank(request.getShift())
                && StrUtil.isNotBlank(request.getOrigin()))
        ) {
            return CommonResp.buildFailMsg("1", "交接班信息生成失败！");
        }
        TraceHandover traceHandover = new TraceHandover();
        String now = LocalDateTime.ofInstant(Instant.now(), ZoneOffset.ofHours(8)).toString();
        String formatTime = now.substring(now.indexOf('T') + 1, now.length() - 2);
        traceHandover.setHoDate(formatTime);
        BeanUtil.copyProperties(request, traceHandover);
        traceHandover.setCreatedUser(request.getUserCode());
        traceHandover.setWarehouse(request.getWarhouse());
        traceHandover.setHoUser(request.getUserCode());
        traceHandover.setStatus("交班");
        traceHandover.setCreateTime(LocalDateTime.now());
        traceHandover.setUpdateTime(LocalDateTime.now());
        traceHandover.setCreatedDate(LocalDateTime.now().format(DateTimeFormatter.ISO_LOCAL_DATE));
        boolean save = save(traceHandover);

        List<TraceStoresloc> traceStoreslocs = storeslocService.getBaseMapper()
                .selectList(Wrappers.<TraceStoresloc>lambdaQuery()
                        .eq(TraceStoresloc::getWarehouse, request.getWarhouse()));

        traceStoreslocs.forEach(traceStoresloc -> {
            List<TraceTool> toolList = toolService.list(Wrappers.<TraceTool>lambdaQuery()
                    .eq(TraceTool::getStoresloc, traceStoresloc.getStoresloc())
                    .eq(TraceTool::getWarehouse, traceStoresloc.getWarehouse())
            );
            // 在库数量
            long onHand = toolList.stream().filter(traceTool -> StrUtil.equals(traceTool.getTlStatus(), "在库")).count();
            // 发料数量
            long issue = toolList.stream().filter(traceTool -> StrUtil.equals(traceTool.getTlStatus(), "借出")).count();
            TraceHandoverDetail maxDetail = detailService.getOne(Wrappers.<TraceHandoverDetail>lambdaQuery()
                    .orderByDesc(TraceHandoverDetail::getTsdId)
                    .last("limit 1")
            );
            toolList.forEach(traceTool -> {
                TraceHandoverDetail detail = new TraceHandoverDetail();
                detail.setTsId(traceHandover.getTsId());
                detail.setTsdId(maxDetail.getTsdId() + 1);
                detail.setWarehouse(traceHandover.getWarehouse());
                detail.setStoresloc(traceHandover.getStation());
                detail.setShift(traceHandover.getShift());
                detail.setWhseIn((int) onHand);
                detail.setCheckReq("盘点需求");
                detail.setHoRemark(request.getHoRemark());
                // 发料数量
                detail.setWhseIssue((int) issue);
                // 盘点数量
                detail.setWhseCheck((0));
                detail.setCreateTime(LocalDateTime.now());
                detail.setUpdateTime(LocalDateTime.now());
                BeanUtil.copyProperties(traceTool, detail);
                boolean detailSave = detailService.save(detail);
                if (!detailSave) {
                    throw new RuntimeException();
                }
            });

        });


        return save ? CommonResp.buildSucsDataListMsg(null, "交接班信息生成成功！") : CommonResp.buildFailMsg("1", "交接班信息生成失败！");
    }

    /**
     * 查询交接班单
     *
     * @param request
     * @return
     */
    @SneakyThrows
    @Override
    public CommonResp getHandoverInfo(HandoverInfoRequest request) {
        if (StrUtil.isNotBlank(request.getShift())) {
            request.setShift(URLDecoder.decode(request.getShift(), "UTF-8"));
        }
        List<TraceHandover> traceHandovers = getBaseMapper().selectList(Wrappers.<TraceHandover>lambdaQuery()
                .like(StrUtil.isNotBlank(request.getHoDate()), TraceHandover::getHoDate, request.getHoDate())
                .like(StrUtil.isNotBlank(request.getShift()), TraceHandover::getShift, request.getShift())
                .like(StrUtil.isNotBlank(request.getWarhouse()), TraceHandover::getWarehouse, request.getWarhouse())
                .eq(StrUtil.isNotBlank(request.getStatus()), TraceHandover::getStatus, request.getStatus())
                .orderByDesc(TraceHandover::getCreateTime));
        return CommonResp.buildSucsDataListMsg(traceHandovers, "数据获取成功！");
    }

    /**
     * 作废交接班单
     *
     * @param request
     * @return
     */
    @Override
    public CommonResp cancelHandoverInfo(CancelHandoverRequest request) {
        List<String> collect = request.getCancelHandoverDtl().stream().map(cancelHandoverDtlItem -> cancelHandoverDtlItem.getTsId()).collect(Collectors.toList());
        List<TraceHandover> traceHandovers = getBaseMapper().selectList(Wrappers.<TraceHandover>lambdaQuery()
                .in(TraceHandover::getTsId, collect)
                .eq(TraceHandover::getCancellation, "1"));

        int[] flag = {0};
        traceHandovers.forEach(traceHandover -> {
            if (!StrUtil.equals("交班", traceHandover.getStatus())) {
                flag[0] = 1;
                return;
            }

            traceHandover.setStatus("作废");
            traceHandover.setCancellation("0");
        });

        if (flag[0] == 1) {
            return CommonResp.buildFailMsg("1", "仅交班状态的交接班单可以作废！");
        } else {
            traceHandovers.forEach(traceHandover -> {
                getBaseMapper().updateById(traceHandover);
                List<TraceHandoverDetail> list = detailService.list(Wrappers.<TraceHandoverDetail>lambdaQuery()
                        .eq(TraceHandoverDetail::getIsHandingOf, "0")
                        .eq(TraceHandoverDetail::getTsId, traceHandover.getTsId()));
                list.forEach(traceHandoverDetail -> traceHandoverDetail.setIsHandingOf("1"));
                detailService.updateBatchById(list);
            });
        }
        return CommonResp.buildSucsDataListMsg(null, "作废交接班单成功！");
    }
}
